package com.hqq.concurrency.promise;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Utility
 * 帮助类
 * Created by heqianqian on 2017/8/1.
 */
public class Utility {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utility.class);

    /**
     * 统计一个文件中字符出现的频率
     *
     * @param fileLocation 文件位置
     * @return Map<Character,Integer>
     */
    public static Map<Character, Integer> characterFrequency(String fileLocation) {
        Map<Character, Integer> characterToFrequency = new HashMap<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileLocation))) {
            String line;
            while ((line = reader.readLine()) != null) {
                for (char c : line.toCharArray()) {
                    if (!characterToFrequency.containsKey(c)) {
                        characterToFrequency.put(c, 1);
                    } else {
                        characterToFrequency.put(c, characterToFrequency.get(c) + 1);
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            e.printStackTrace();
        }
        return characterToFrequency;
    }

    /**
     * 返回出现次数最少的字符
     */
    public static Character lowestFrequencyChar(Map<Character, Integer> characterToFrequency) {
        Iterator<Map.Entry<Character, Integer>> iterator = characterToFrequency.entrySet().iterator();
        Map.Entry<Character, Integer> first = iterator.next();
        Integer lowestCFrequency =first.getValue();
        Character lowestChar =first.getKey();
        while (iterator.hasNext()) {
            Map.Entry<Character, Integer> next = iterator.next();
            if (lowestCFrequency < next.getValue()) {
                lowestCFrequency = next.getValue();
                lowestChar = next.getKey();
            }
        }
        return lowestChar;
    }

    /**
     * 返回文件行数
     *
     * @param fileLocation 文件位置
     * @return 文件行数
     */
    public static int countLines(String fileLocation) {
        int countLines = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(fileLocation))) {
            String line;
            while ((line = reader.readLine()) != null) {
                countLines++;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            e.printStackTrace();
        }
        return countLines;
    }

    /**
     * Downloads the contents from the given urlString, and stores it in a temporary directory.
     *
     * @return the absolute path of the file downloaded.
     */
    public static String downloadFile(String urlString) throws MalformedURLException, IOException {
        LOGGER.info("Downloading contents from url: {}", urlString);
        URL url = new URL(urlString);
        File file = File.createTempFile("promise_pattern", null);
        try (Reader reader = new InputStreamReader(url.openStream());
             BufferedReader bufferedReader = new BufferedReader(reader);
             FileWriter writer = new FileWriter(file)) {
            for (String line; (line = bufferedReader.readLine()) != null; ) {
                writer.write(line);
                writer.write("\n");
            }
            LOGGER.info("File downloaded at: {}", file.getAbsolutePath());
            return file.getAbsolutePath();
        } catch (IOException ex) {
            throw ex;
        }
    }


}
